<script setup>
import { ref, computed, watch } from 'vue'
import BasePieChart from '@/components/chart/BasePieChart.vue'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { useCompanyStore } from '@/stores/company'
import { getAllSubCategoryReportApi } from '@/api/category'
import { handleError } from '@/utils/handleError'

const props = defineProps({
    title: {
        type: String,
        default: '用途用水量'
    },
    height: {
        type: String,
        default: '230px'
    }
})

const companyStore = useCompanyStore()
const pieChartTime = ref(null)
const pieChartData = ref([])
const pieChartLoading = ref(false)

// 获取用途总数据
async function getSubCategoryTotalData(start_time, end_time) {
    if (!start_time || !end_time) return null

    if (!companyStore?.currentCompany?.id) {
        console.warn('当前公司ID不存在');
        return null;
    }

    try {
        let res = await getAllSubCategoryReportApi({
            id: companyStore.currentCompany.id,
            start_time,
            end_time,
            type: 1,
        })

        if (!res || !res.aggregated_data) {
            console.warn('获取用途数据返回格式不正确:', res);
            return null;
        }

        return res.aggregated_data
    } catch (error) {
        handleError(error, '获取用途数据失败')
        return null
    }
}

// 监听公司ID变化
watch(() => companyStore.currentCompany?.id, async () => {
    if (pieChartTime.value) {
        pieChartLoading.value = true
        try {
            let data = await getSubCategoryTotalData(pieChartTime.value.start_time, pieChartTime.value.end_time)
            if (data) {
                if (!Array.isArray(data)) {
                    console.warn('饼图数据格式不正确, 期望数组但收到:', typeof data);
                    pieChartData.value = [];
                    return;
                }

                pieChartData.value = data.flat()
                    .map(item => {
                        if (!item) return null;
                        const usage = Array.isArray(item.usage) ? item.usage : [];
                        return {
                            name: item.subcategory || '其他',
                            value: usage.reduce((acc, meter) => {
                                const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                                return acc + used;
                            }, 0),
                            subcategory: item.subcategory
                        };
                    })
                    .filter(item => item !== null && item.value > 0)
                    .sort((a, b) => b.value - a.value)
            } else {
                pieChartData.value = [];
            }
        } catch (error) {
            handleError(error, '获取饼图数据失败')
            pieChartData.value = [];
        } finally {
            pieChartLoading.value = false
        }
    }
})

// 监听饼图时间变化
watch(() => pieChartTime.value, async (newValue) => {
    if (newValue) {
        pieChartLoading.value = true
        try {
            let data = await getSubCategoryTotalData(newValue.start_time, newValue.end_time)
            if (data) {
                if (!Array.isArray(data)) {
                    console.warn('饼图数据格式不正确, 期望数组但收到:', typeof data);
                    pieChartData.value = [];
                    return;
                }

                pieChartData.value = data.flat()
                    .map(item => {
                        if (!item) return null;
                        const usage = Array.isArray(item.usage) ? item.usage : [];
                        return {
                            name: item.subcategory || '其他',
                            value: usage.reduce((acc, meter) => {
                                const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                                return acc + used;
                            }, 0),
                            subcategory: item.subcategory
                        };
                    })
                    .filter(item => item !== null && item.value > 0)
                    .sort((a, b) => b.value - a.value)
            } else {
                pieChartData.value = [];
            }
        } catch (error) {
            handleError(error, '获取饼图数据失败')
            pieChartData.value = [];
        } finally {
            pieChartLoading.value = false
        }
    }
}, { immediate: true })
</script>

<template>
    <div class="card-header">
        <span>{{ title }}</span>
        <CustomDateRadio @update:modelValue="pieChartTime = $event"></CustomDateRadio>
    </div>
    <BasePieChart :height="height" :showLegend="false" :data="pieChartData" unit="m³" />
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
</style>